<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->

<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-7xl mx-auto px-4">
      <div class="flex gap-8">
        <!-- 左侧用户信息面板 -->
        <div class="w-1/3 space-y-6">
          <div class="bg-white rounded-lg p-6 shadow-sm">
            <div class="flex flex-col items-center">
              <div class="w-24 h-24 rounded-full overflow-hidden mb-4">
                <img
                  :src="userAvatar"
                  class="w-full h-full object-cover"
                  alt="用户头像"
                />
              </div>
              <div class="flex items-center gap-2 mb-2">
                <h2 class="text-xl font-bold">{{ userInfo.name }}</h2>
                <a-button
                  type="link"
                  class="!rounded-button"
                  @click="showEditName = true"
                >
                  <edit-outlined />
                </a-button>
              </div>
              <p class="text-gray-600 text-center mb-4">{{ userInfo.bio }}</p>
              <div class="w-full grid grid-cols-2 gap-4">
                <div class="text-center p-3 bg-gray-50 rounded-lg">
                  <div class="text-2xl font-bold text-green-600">
                    {{ acCount }}
                  </div>
                  <div class="text-sm text-gray-600">解题总数</div>
                </div>
                <div class="text-center p-3 bg-gray-50 rounded-lg">
                  <div class="text-2xl font-bold text-purple-600">
                    {{ messageCount }}
                  </div>
                  <div class="text-sm text-gray-600">提交反馈</div>
                </div>
              </div>
            </div>
          </div>
          <div class="bg-white rounded-lg p-6 shadow-sm">
            <h3 class="text-lg font-bold mb-4">社交信息</h3>
            <div class="space-y-3">
              <a
                :href="userInfo.github"
                target="_blank"
                class="flex items-center gap-2 text-gray-700 hover:text-blue-600"
              >
                <github-outlined />
                <span>GitHub</span>
              </a>
            </div>
          </div>
        </div>
        <!-- 右侧数据统计区域 -->
        <div class="w-2/3 space-y-6">
          <div class="grid grid-cols-1 gap-4">
            <div class="bg-white rounded-lg p-6 shadow-sm">
              <h3 class="text-lg font-bold mb-4">解题统计</h3>
              <div class="grid grid-cols-3 gap-4 mb-6">
                <div class="text-center p-3 bg-gray-50 rounded-lg">
                  <div class="text-xl font-bold text-green-600">
                    {{ acNumberData.easyCount }}
                  </div>
                  <div class="text-sm text-gray-600">简单题</div>
                </div>
                <div class="text-center p-3 bg-gray-50 rounded-lg">
                  <div class="text-xl font-bold text-orange-500">
                    {{ acNumberData.mediumCount }}
                  </div>
                  <div class="text-sm text-gray-600">中等题</div>
                </div>
                <div class="text-center p-3 bg-gray-50 rounded-lg">
                  <div class="text-xl font-bold text-red-600">
                    {{ acNumberData.hardCount }}
                  </div>
                  <div class="text-sm text-gray-600">困难题</div>
                </div>
              </div>
              <div>
                <h4 class="text-base font-medium mb-3">最近通过</h4>
                <div class="space-y-2">
                  <div
                    v-for="(item, index) in recentSolved"
                    :key="index"
                    class="flex items-center justify-between p-2 hover:bg-gray-50 rounded"
                  >
                    <span class="text-gray-900">{{ item.title }}</span>
                    <a
                      :class="getDifficultyClass(item.hardRant)"
                      v-html="getDifficultyText(item.hardRant)"
                    ></a>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="bg-white rounded-lg p-6 shadow-sm">
            <div class="items-center mb-4">
              <h3 class="text-lg font-bold">累计提交图</h3>
              <HotPhoto />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 修改昵称弹窗 -->
    <a-modal
      v-model:visible="showEditName"
      title="修改昵称"
      @ok="handleEditName"
      :okText="'确定'"
      :cancelText="'取消'"
    >
      <a-input v-model="newName" placeholder="请输入新昵称" />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, UnwrapRef } from "vue";
import { EditOutlined, GithubOutlined } from "@ant-design/icons-vue";
import * as echarts from "echarts";
import { message } from "ant-design-vue";
import {
  UserControllerService,
  UserUpdateMyRequest,
} from "../../xiongoj_backendapi";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { PersonCenterControllerService } from "../../backendapi";

const newName = ref();
const router = useRouter();
const store = useStore();
const messageCount = ref();
const acCount = ref();
const userAvatar = store.state.user?.loginUser?.userAvatar;
//todo userInfo对接后端的数据
const userInfo = ref({
  name: store.state.user?.loginUser?.userName,
  bio: "前端架构师 / 算法爱好者 / 开源贡献者，致力于用技术改变世界",
  solvedCount: acCount.value,
  medals: messageCount.value,
  github: "https://github.com/zhaomingyu",
});

const showEditName = ref(false);
const heatmapRange = ref("365");
const trendRange = ref("30");

//改变里面本地存储在localStorage里面的东西
const handleEditName = async () => {
  if (newName.value != null) {
    userInfo.value.name = newName.value;
    showEditName.value = false;
    const userUpdateRequest: UserUpdateMyRequest = {
      userName: newName.value,
    };
    const res = UserControllerService.updateMyUserUsingPost(userUpdateRequest);
    newName.value = "";
  } else {
    message.error("你没有输入名字");
  }
};
//侧边栏请求数据
const getAcCountAndMessageAccount = async () => {
  try {
    const userId = store.state.user?.loginUser?.id;
    if (!userId) {
      console.error("用户 ID 为空，无法获取数据");
      return;
    }

    acCount.value = await PersonCenterControllerService.getAcCountUsingGet(
      userId
    );
    console.log(acCount.value);

    messageCount.value = await PersonCenterControllerService.getMessageUsingGet(
      userId
    );
  } catch (error) {
    console.error("获取数据时出错:", error);
  }
};

const acNumberData = ref<{
  easyCount: number | undefined;
  mediumCount: number | undefined;
  hardCount: number | undefined;
}>({
  easyCount: undefined,
  mediumCount: undefined,
  hardCount: undefined,
});
//通过的简单，困难，题目数量
const fetchAcNumber = async (userId: string) => {
  try {
    const response = await PersonCenterControllerService.getAcNumberUsingGet(
      userId
    );
    if (response.data) {
      acNumberData.value.easyCount = response.data.easyCount;
      acNumberData.value.mediumCount = response.data.mediumCount;
      acNumberData.value.hardCount = response.data.hardCount;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  }
};

// 最近通过
import type { BaseResponse_List_RecentACQuestion_ } from "../../backendapi";
import HotPhoto from "@/components/HotPhoto.vue"; // 根据实际路径修改
const recentSolved = ref<Array<{ hardRant?: string; title?: string }>>([]);
const fetchRecentQuestions = async (userId: string) => {
  try {
    const response: BaseResponse_List_RecentACQuestion_ =
      await PersonCenterControllerService.getRecentQuestionUsingGet(userId);
    if (response.data) {
      recentSolved.value = response.data;
    }
  } catch (error) {
    console.error("获取最近解决的问题数据失败:", error);
  }
};

onMounted(() => {
  //获取到通过的简单中等困难的题目
  fetchAcNumber(store.state.user?.loginUser?.id);
  //获取到提交反馈数量
  getAcCountAndMessageAccount();
  //最近通过
  fetchRecentQuestions(store.state.user?.loginUser?.id);
});

function generateTrendDates() {
  const dates = [];
  for (let i = 30; i > 0; i--) {
    const date = new Date();
    date.setDate(date.getDate() - i);
    dates.push(echarts.format.formatTime("MM-dd", date));
  }
  return dates;
}
// 定义获取难度样式类的方法
const getDifficultyClass = (difficulty: string | undefined) => {
  if (difficulty === "S") {
    return "text-green-500";
  } else if (difficulty === "M") {
    return "text-yellow-500";
  } else if (difficulty === "L") {
    return "text-red-500";
  }
  return "";
};
// 定义获取难度文本的方法
const getDifficultyText = (difficulty: string | undefined) => {
  if (difficulty === "S") {
    return "简单";
  } else if (difficulty === "M") {
    return "中等";
  } else if (difficulty === "L") {
    return "困难";
  }
  return "";
};
function generateTrendData() {
  const basePattern = [8, 12, 10, 15, 13, 9, 7];
  const trend = [];
  for (let i = 0; i < 30; i++) {
    const dayOfWeek = i % 7;
    const baseValue = basePattern[dayOfWeek];
    const weekTrend = Math.floor(i / 7) * 2; // 逐渐增长趋势
    const randomVariation = Math.floor(Math.random() * 4) - 2; // -2 到 +2 的随机变化
    trend.push(Math.max(0, baseValue + weekTrend + randomVariation));
  }
  return trend;
}
</script>

<style scoped>
:deep(.ant-select-selector) {
  border-radius: 20px !important;
}
</style>
